<template>
	<!-- 面包屑 -->
	<el-breadcrumb separator="/">
		<el-breadcrumb-item :to="{path:'/welcome'}">首页</el-breadcrumb-item>
		<el-breadcrumb-item>公司管理</el-breadcrumb-item>
	</el-breadcrumb>
	<!-- 行内表单 -->
	<el-form :inline="true" :model="formInline" class="demo-form-inline">
		<el-form-item label="公司名">
			<el-input v-model="formInline.companyName" placeholder="请输入公司名" clearable @clear="query" />
		</el-form-item>
		<el-form-item label="公司地址">
			<el-input v-model="formInline.companyAddress" placeholder="请输入公司地址" clearable @clear="query" />
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="seek">搜索</el-button>
			<el-button type="primary" @click="openAddDialog">新增公司</el-button>
			<el-button type="danger" @click="removeAll">批量删除</el-button>
		</el-form-item>
	</el-form>

	<!-- 新增/编辑公司弹出框 -->
	<el-dialog v-model="dialogVisible" :title="title" width="500px" @close="resetForm">
		<el-form 
			:model="form" 
			:rules="rules" 
			ref="formRef" 
			label-width="100px" 
			style="max-width: 600px"
		>
			<el-form-item label="公司名称" prop="companyName">
				<el-input v-model="form.companyName" placeholder="请输入公司名称" />
			</el-form-item>
			<el-form-item label="公司地址" prop="companyAddress">
				<el-input v-model="form.companyAddress" placeholder="请输入公司地址" />
			</el-form-item>
			<el-form-item label="公司电话" prop="companyTel">
				<el-input v-model="form.companyTel" placeholder="请输入公司电话" />
			</el-form-item>
			<el-form-item label="公司邮箱" prop="companyEmail">
				<el-input v-model="form.companyEmail" placeholder="请输入公司邮箱" />
			</el-form-item>
			<el-form-item label="公司介绍">
				<el-input 
					type="textarea" 
					v-model="form.companyDescription" 
					placeholder="请输入公司介绍" 
					rows="4"
				/>
			</el-form-item>
			<el-form-item label="公司二维码">
				<el-input v-model="form.companyErCode" placeholder="请输入二维码路径" />
				<el-image 
					v-if="form.companyErCode"
					:src="getFullQrCodeUrl(form.companyErCode)" 
					alt="二维码预览" 
					style="width: 100px; height: 100px; margin-top: 10px"
					fit="contain"
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">确定</el-button>
			</div>
		</template>
	</el-dialog>

	<!-- 表格 -->
	<div>
		<el-table ref="multipleTableRef" border :data="tableData" row-key="id" style="width: 100%"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column property="id" label="ID" width="80" />
			<el-table-column property="companyName" label="公司名称" />
			<el-table-column property="companyAddress" label="公司地址" />
			<el-table-column property="companyTel" label="公司电话" />
			<el-table-column property="companyEmail" label="公司邮箱" />
			<el-table-column property="companyDescription" label="公司介绍" width="200" />
			<el-table-column label="公司二维码" width="120">
				<template #default="scope">
					<el-image 
						v-if="scope.row.companyErCode"
						:src="getFullQrCodeUrl(scope.row.companyErCode)" 
						alt="二维码" 
						style="width: 60px; height: 60px"
						fit="contain"
					/>
					<span v-else>无</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" width="200">
				<template #default='scope'>
					<el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
	</div>

	<!-- 分页 -->
	<el-pagination 
		v-model:current-page="formInline.pageNum" 
		v-model:page-size="formInline.pageSize"
		:page-sizes="[5, 10, 15, 20]" 
		layout="total, sizes, prev, pager, next, jumper" 
		:total="total"
		@size-change="handleSizeChange" 
		@current-change="handleCurrentChange" 
		style="margin-top: 15px; text-align: right" 
	/>
</template>

<script lang="ts" setup>
	import { onMounted, reactive, ref, computed } from 'vue'
	import type { TableInstance, FormInstance } from 'element-plus'
	import axios from 'axios'
	import { ElMessage, ElMessageBox } from 'element-plus'

	// 后端接口基础地址
	const baseApi = 'http://localhost:8080/company';
	// 文件访问基础路径（根据实际情况修改）
	const fileBaseUrl = 'http://localhost:8080';

	// 行内表单数据
	const formInline = reactive({
		companyName: '',
		companyAddress: '',
		pageNum: 1,
		pageSize: 10
	})
	
	// 表单验证规则
	const rules = {
		companyName: [
			{ required: true, message: '请输入公司名称', trigger: 'blur' },
			{ max: 50, message: '公司名称不能超过50个字符', trigger: 'blur' }
		],
		companyAddress: [
			{ max: 200, message: '公司地址不能超过200个字符', trigger: 'blur' }
		],
		companyTel: [
			{ pattern: /^[\d-]{6,20}$/, message: '请输入有效的电话号码', trigger: 'blur' }
		],
		companyEmail: [
			{ type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
		]
	}

	// 弹出框相关
	const dialogVisible = ref(false);
	const title = ref('新增公司')
	const formRef = ref<FormInstance>()
	const form = ref({
		id: '',
		companyName: '',
		companyAddress: '',
		companyTel: '',
		companyEmail: '',
		companyDescription: '',
		companyErCode: ''
	})

	// 表格数据
	const multipleTableRef = ref<TableInstance>()
	const tableData = ref([]);
	const total = ref(0);
	const multipleSelection = ref<number[]>([])

	// 获取完整的二维码图片URL
	const getFullQrCodeUrl = computed(() => {
		return (path: string) => {
			if (!path) return '';
			// 判断是否是完整URL
			return path.startsWith('http') ? path : `${fileBaseUrl}${path}`;
		}
	})

	// 打开新增对话框
	const openAddDialog = () => {
		resetForm();
		title.value = '新增公司';
		dialogVisible.value = true;
	}

	// 打开编辑对话框
	const openEditDialog = (row: any) => {
		resetForm();
		title.value = '编辑公司';
		// 深拷贝行数据到表单
		form.value = JSON.parse(JSON.stringify(row));
		dialogVisible.value = true;
	}

	// 重置表单
	const resetForm = () => {
		form.value = {
			id: '',
			companyName: '',
			companyAddress: '',
			companyTel: '',
			companyEmail: '',
			companyDescription: '',
			companyErCode: ''
		}
		if (formRef.value) {
			formRef.value.resetFields();
		}
	}

	// 提交表单（新增/编辑）
	const submitForm = async () => {
	  // 表单验证
	  if (!formRef.value) return;
	  try {
	    await formRef.value.validate();
	    
	    if (form.value.id) {
	      // 编辑操作：适配后端 @PutMapping("/company") 接口（无路径参数）
	      await axios.put(baseApi, form.value); // 移除路径中的 ${form.value.id}
	      ElMessage.success('编辑成功');
	    } else {
	      // 新增操作（不变）
	      await axios.post(baseApi, form.value);
	      ElMessage.success('添加成功');
	    }
	    
	    dialogVisible.value = false;
	    query(); // 重新查询数据
	  } catch (error: any) {
	    // 验证失败或请求错误处理
	    if (error.name === 'ValidationError') {
	      return; // 表单验证失败不处理
	    }
	    // 错误信息优先取后端返回的message，否则取默认错误
	    ElMessage.error(`操作失败: ${error.response?.data?.message || error.message}`);
	  }
	};

	// 搜索
	const seek = () => {
		formInline.pageNum = 1; // 搜索时重置到第一页
		query();
	}

	// 数据查询
	const query = () => {
		axios.get(`${baseApi}/page`, {
			params: formInline
		})
			.then((resp) => {
				tableData.value = resp.data.data.list || [];
				total.value = resp.data.data.total || 0;
			})
			.catch(error => {
				ElMessage.error('数据加载失败：' + error.message);
				tableData.value = [];
				total.value = 0;
			})
	}

	// 页面加载时初始化数据
	onMounted(() => {
		query();
	})

	// 分页处理
	const handleSizeChange = (val: number) => {
		formInline.pageSize = val;
		query();
	}
	const handleCurrentChange = (val: number) => {
		formInline.pageNum = val;
		query();
	}

	// 单个删除
	const remove = (id: number) => {
		ElMessageBox.confirm(
			'此操作将删除该公司数据, 是否继续?',
			'确认删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				return axios.delete(`${baseApi}/${id}`);
			})
			.then(() => {
				ElMessage.success('删除成功');
				query();
			})
			.catch(error => {
				if (error !== 'cancel') {
					ElMessage.error('删除失败：' + (error.message || '未知错误'));
				}
			})
	}

	// 批量删除
	const handleSelectionChange = (val: any[]) => {
		multipleSelection.value = val.map(item => item.id);
	}
	
	const removeAll = () => {
		if (multipleSelection.value.length === 0) {
			ElMessage.warning('请先选择需要删除的数据');
			return;
		}
		
		ElMessageBox.confirm(
			`此操作将删除选中的${multipleSelection.value.length}条数据, 是否继续?`,
			'批量删除',
			{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				return axios.delete(baseApi, {
					params: { ids: multipleSelection.value.join(',') }
				});
			})
			.then(() => {
				ElMessage.success('批量删除成功');
				query();
				// 清空选择
				if (multipleTableRef.value) {
					multipleTableRef.value.clearSelection();
				}
			})
			.catch(error => {
				if (error !== 'cancel') {
					ElMessage.error('批量删除失败：' + (error.message || '未知错误'));
				}
			})
	}
</script>

<style>
	/* 面包屑样式 */
	.el-breadcrumb {
		margin-bottom: 15px;
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.demo-form-inline .el-input {
		--el-input-width: 220px;
	}

	/* 表格操作按钮样式 */
	.el-table .el-button {
		margin-right: 5px;
	}
</style>